//
//  HotelIntelligentRankingView.swift
//  AirTravel
//
//  Created by apple on 2021/7/15.
//

import UIKit
protocol HotelIntelligentRankingDelegate:NSObjectProtocol {
    func intelligentRankingClick(data:Dictionary<String,Any>)
}

class HotelIntelligentRankingView: UIView {

    var contentView:UIView!
    weak var delegate: HotelIntelligentRankingDelegate?
    
    @IBOutlet weak var tabView: UITableView!
    let identifyIR = "IntelligentRankingCell"
    var dataSouce : Array<Any>?
    var number = 0
    

    // 初始化时将xib中的view添加进来
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView = loadViewFromNib()
        contentView.frame = self.bounds
        contentView.backgroundColor = UIColor.white
        self.insertSubview(contentView, at: 0)
        
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "IntelligentRankingCell", bundle: nil), forCellReuseIdentifier: identifyIR)
        self.tabView.rowHeight = 50
    }
    
    // 初始化时将xib中的view添加进来
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // 加载xib
    func loadViewFromNib() -> UIView {
        let className = type(of: self)
        let bundle = Bundle(for: className)
        let name = NSStringFromClass(className).components(separatedBy: ".").last
        let nib = UINib(nibName: name!, bundle: bundle)
        let view = nib.instantiate(withOwner: self, options: nil).first as! UIView
        view.backgroundColor = UIColor.clear
        return view
    }
    
    func setUpData(array:Array<Any>) {
        self.dataSouce = array
        self.tabView.reloadData()
    }
}

extension HotelIntelligentRankingView:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifyIR) as! IntelligentRankingCell
        cell.selectionStyle = .none
        if self.number == indexPath.row {
            cell.contentLab.textColor = Orange_COLOR
        }else{
            cell.contentLab.textColor = UIColor.black
        }
        if let array = self.dataSouce {
            let dic = array[indexPath.row] as? Dictionary<String,Any>
            cell.contentLab.text = "\(dic?["name"] ?? "")"
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        self.number = indexPath.row
        if let array = self.dataSouce {
            let dic = array[indexPath.row] as? Dictionary<String,Any> ?? [:]
            self.delegate?.intelligentRankingClick(data: dic)
        }
        self.tabView.reloadData()
    }
}
